package com.kikoulol.jarmoryextractor.utils;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;

import com.kikoulol.jarmoryextractor.Armory;

public class Utils {

	public static int connectionTry = 0;
	public static DocumentBuilderFactory xmlFactory = DocumentBuilderFactory.newInstance();

	public static String convertStreamToString(InputStream is) throws IOException {
		/*
		 * To convert the InputStream to String we use the BufferedReader.readLine()
		 * method. We iterate until the BufferedReader return null which means
		 * there's no more data to read. Each line will appended to a StringBuilder
		 * and returned as String.
		 */
		if (is != null) {
			StringBuilder sb = new StringBuilder();
			String line;

			try {
				BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
				while ((line = reader.readLine()) != null) {
					sb.append(line).append("\n");
				}
			} finally {
				is.close();
			}
			return sb.toString();
		} else {       
			return "";
		}
	}

	public static void downloadFile(String url, String to) throws IOException {

		DataInputStream in=null;
		DataOutputStream out=null;
		FileOutputStream fOut=null;

		try{
			URL remoteFile=new URL(url);
			URLConnection fileStream=remoteFile.openConnection();
			fileStream.setRequestProperty( "User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1" );

			// Open the input streams for the remote file
			File folder = new File(to);
			folder.getParentFile().mkdirs();
			fOut=new FileOutputStream(to);


			// Open the output streams for saving this file on disk
			out=new DataOutputStream(fOut);

			in=new DataInputStream(fileStream.getInputStream());

			// Read the remote on save save the file
			int data;
			while((data=in.read())!=-1){
				fOut.write(data);
			}  
			//System.out.println("Download of " + url + " is complete." );   
		} catch (Exception e){
			e.printStackTrace();
		} finally {
			try{
				in.close();
				fOut.flush(); 
				fOut.close();      
			} catch(Exception e){e.printStackTrace();}

		}
	}

	public static String getLocalUrl(String webUrl) {
		return Armory.cacheFolder + "/" + (webUrl.split("/")[2]+ "-" + webUrl.split("/")[3] + ".xml").replace("?", "-");
	}
	
	public static String getArmoryXml(String armoryUrl) throws IOException {
		System.out.println("getting : " + armoryUrl);
		//String filePath = Armory.cacheFolder + "/" + (armoryUrl.split("/")[2]+ "-" + armoryUrl.split("/")[3] + ".xml").replace("?", "-"); 
		String filePath = getLocalUrl(armoryUrl);
		File file = new File(filePath);

		if (file.exists()) {
			return readFile(file);
		}
		else {
			downloadFile(armoryUrl,filePath);	
			String nextLine;
			URL url = null;
			URLConnection urlConn = null;
			InputStreamReader  inStream = null;
			BufferedReader buff = null;
			try{
				url  = new URL(armoryUrl);
				Wait.manySec(2);
				connectionTry++;
				urlConn = url.openConnection();
				urlConn.setRequestProperty( "User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1" );
				inStream = new InputStreamReader(urlConn.getInputStream());
				buff= new BufferedReader(inStream);

				StringBuffer reader = new StringBuffer();

				// Read and print the lines from index.html
				while (true){
					nextLine =buff.readLine();  
					if (nextLine !=null){
						reader.append(nextLine);
					}
					else{
						break;
					} 
				}
				return reader.toString();

			} catch(MalformedURLException e){
				System.out.println("Please check the URL:" + e.toString() );
			} catch(IOException  e1){
				System.out.println("Can't read  from the Internet: "+	e1.toString() );
			}
		}
		return null;
	}

	static public String readFile(File aFile) {
		//System.out.println("Reading from hd : " + aFile.getName());
		//...checks on aFile are elided
		StringBuilder contents = new StringBuilder();

		try {
			//use buffering, reading one line at a time
			//FileReader always assumes default encoding is OK!
			BufferedReader input =  new BufferedReader(new FileReader(aFile));
			try {
				String line = null; //not declared within while loop
				/*
				 * readLine is a bit quirky :
				 * it returns the content of a line MINUS the newline.
				 * it returns null only for the END of the stream.
				 * it returns an empty String if two newlines appear in a row.
				 */
				while (( line = input.readLine()) != null){
					contents.append(line);
					contents.append(System.getProperty("line.separator"));
				}
			}
			finally {
				input.close();
			}
		}
		catch (IOException ex){
			ex.printStackTrace();
		}

		return contents.toString();
	}


	public static Element getXmlRootElement(File file) throws ParserConfigurationException, SAXException, IOException {
		DocumentBuilder constructeur = xmlFactory.newDocumentBuilder();
		Document document = constructeur.parse(file);
		Element racine = document.getDocumentElement();
		return racine;
	}

	public static Element getXmlRootElement(String xml) throws ParserConfigurationException, SAXException, IOException {
		DocumentBuilder constructeur = xmlFactory.newDocumentBuilder();
		InputStream stream = new ByteArrayInputStream(xml.getBytes("UTF-8"));
		Document document = constructeur.parse(stream);
		Element racine = document.getDocumentElement();
		return racine;
	}

}
